<?php
/**
 * Created by PhpStorm.
 * User: User
 * Date: 2017/11/21
 * Time: 16:14
 */

namespace Kinfy\View;

use kinfy\Config;

class View
{

    //模板所用的编译器引擎
    protected $compiler = null;
    //模板资源所在的根目录
    protected $base_dir = '';
    //模板资源文件的缓存文件夹
    protected $cache_dir = '';
    //模板主题
    protected $theme = '';
    //模板主题根目录
    protected $base = '';
    //模板主题缓存目录
    protected $cache = '';
    //模板后缀
    protected $suffix = '';

    protected $data = [];

    public function __construct($engine = '')
    {
        if (!$engine) {
            $engine = Config::get('view.engine');
        }
        $engine = "\\Kinfy\\View\\Engine\\{$engine}";
        $this->compiler = new $engine();
        $this->base_dir = Config::get('view.base_dir');
        $this->cache_dir = Config::get('view.cache_dir');
        $this->theme = Config::get('view.theme');

        $this->base = $this->base_dir . '/' . $this->theme . '/';
        $this->cache = $this->cache_dir . '/' . $this->theme . '/';
        $this->suffix = '.tpl.php';
    }

    public function set($name, $value)
    {
        $this->data[$name] = $value;
    }

    public function show($tpl)
    {
        extract($this->data);
        $tpl_cache = $this->cache . $tpl . $this->suffix;

        if (Config::get('view.auto_refresh') || !file_exists($tpl_cache)) {
            $this->compiling($tpl);
        }
        include($tpl_cache);
    }


    public function compiling($tpl)
    {
        $this->compiler->setBaseDir($this->base);
        $this->compiler->addSubTpl($tpl);
        //模板读取
        $tpl_file = $this->base . $tpl . $this->suffix;
        $this->compiler->template = file_get_contents($tpl_file);
        //layout
        $this->compiler->extendsExp();
        //调用，要先处理
        $this->compiler->includeExp();
        //判断语句
        $this->compiler->ifExp();
        $this->compiler->elseifExp();
        $this->compiler->elseExp();
        $this->compiler->endifExp();
        //循环语句
        $this->compiler->loopExp();
        $this->compiler->endloopExp();
        //变量
        $this->compiler->varExp();
        //模板写入缓存
        $tpl_cache = $this->cache . $tpl . $this->suffix;
        if (!is_dir($this->cache)) {
            mkdir($this->cache);
        }
        //加时间判断，智能更新模板
        $check = '
        <?php
        $tpls = '.var_export($this->compiler->getSubTpls(),true).';
        $base_dir = "'.$this->base.'";
        foreach($tpls as $tpl){
            if(filemtime($base_dir.$tpl.".tpl.php") > filemtime(__FILE__)){
                    unlink(__FILE__);
            }
        }
        ?>';


        file_put_contents($tpl_cache, $check.$this->compiler->template);

    }

}